#ifndef FILE_HANDLER
#define FILE_HANDLER

#include<string>
#include<unistd.h>
#include<sys/stat.h>
#include"Defines.cpp"

class FileHandler
{
    private:
    FILE* _file = NULL;
    std::string _filePath;
    public:
    FileHandler(std::string path, std::string mode = "r")
    {
        _filePath = path;
        //判断文件是否存在
        if(IsFileExist() == false)
        {
            PrintLine("文件不存在 [%s]", _filePath.c_str());
            return;
        }
        //打开文件
        _file = fopen(_filePath.c_str(), mode.c_str());
        if(_file == NULL)
        {
            PrintLine("文件打开失败 [%s]", _filePath.c_str());
            return;
        }
    }

    int Read(char *buff, int length)
    {
        int ret = fread(buff, sizeof(char), length, _file);
        return ret;
    }

    long GetFileSize()
    {
        return GetFileSize(_filePath);
    }

    bool IsDirectoryFile()
    {
        return IsDirectoryFile(_filePath);
    }

    bool IsOrdinaryFile()
    {
        return IsOrdinaryFile(_filePath);
    }

    bool IsFileExist()
    {
        return IsFileExist(_filePath);
    }

    //静态函数
    static long GetFileSize(std::string path)
    {
        FILE *file = fopen(path.c_str(), "r");
        if(file == NULL)
        {
            PrintLine("文件指针为空 %s", path);
            return -1;
        }
        fseek(file, 0L, SEEK_END);
        long ret = ftell(file);
        fclose(file);
        return ret;
    }

    static bool IsDirectoryFile(std::string path)
    {
        struct stat st;
        stat(path.c_str(), &st);
        return S_ISDIR(st.st_mode);
    }

    static bool IsOrdinaryFile(std::string path)
    {
        struct stat st;
        stat(path.c_str(), &st);
        return S_ISREG(st.st_mode);
    }

    static bool IsFileExist(std::string path)
    {
        return access(path.c_str(), F_OK) == 0 && (IsOrdinaryFile(path) || IsDirectoryFile(path));
    }
};

#endif